#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QWidget(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->webView->load(QUrl("http://l2nemerian.seobrya.com/updater/"));

    connect(ui->quit_boutton, SIGNAL(clicked()), this, SLOT(my_quit()));
    connect(ui->start_boutton, SIGNAL(clicked()), this, SLOT(execute()));
    connect(ui->FC_boutton, SIGNAL(clicked()), this, SLOT(fullCheck()));

    ui->FC_boutton->setEnabled(false);
    ui->start_boutton->setEnabled(false);
    ui->total_pbar->setMaximum(1);
    file_dl = 0;
}

MainWindow::~MainWindow()
{
    if (threadList != 0 && threadList->isRunning())
    {
        threadList->quit();
        delete threadList;
    }
    delete ui;
}

void MainWindow::fullCheck()
{
    getFileList(false);
}

void MainWindow::execute()
{
    if (QProcess::startDetached("\"system/L2.exe\""))
        this->my_quit();
}

void MainWindow::closeEvent ( QCloseEvent * event )
{
    my_quit();
}

void MainWindow::my_quit()
{
    if(QFile::exists("update.lst"))
        QFile::remove("update.lst");
    close();
}

void MainWindow::downloadlst()
{
    ThreadDownload = new TDownload(this, QStringList("update.lst"));
    connect(ThreadDownload, SIGNAL(updateProgress(int, int)), this, SLOT(updateDataReadProgress(int,int)));
    ui->statusLabel->setText(tr("Downloading."));
    ThreadDownload->start();
    QEventLoop loop;
    connect(ThreadDownload, SIGNAL(done()), &loop, SLOT(quit()));
    loop.exec();
    ThreadDownload->wait();
    delete ThreadDownload;
    getFileList(true);
}

QString MainWindow::CalcSha1(QString Path)
{
        QFile FileToHash(Path);
        QByteArray ba;
        QString HashOutput;
        QCryptographicHash CPU(QCryptographicHash::Sha1);
        if (FileToHash.open(QIODevice::ReadOnly))
        {
                while (!FileToHash.atEnd())
                {
                        ba = FileToHash.read(1024);
                        CPU.addData(ba);
                }
                FileToHash.close();
                ba = CPU.result();
                HashOutput = ba.toHex();
                return HashOutput;
        }
        else
        {
                HashOutput = "ERR";
                return HashOutput;
        }
}

void MainWindow::getFileList(bool critical)
{
    if (critical == true)
        ui->statusLabel->setText(tr("Downloading Critical update."));
    else
        ui->statusLabel->setText(tr("Downloading all invalid file."));
    ui->FC_boutton->setEnabled(false);
    ui->start_boutton->setEnabled(false);
    threadList = new ListCalc(this, critical);
    //connect
    connect(threadList, SIGNAL(checkFile(QString)), this, SLOT(setStatusLabel(QString)));
    connect(threadList, SIGNAL(giveModel(QStringListModel*)), this, SLOT(setModel(QStringListModel*)));
    connect(threadList, SIGNAL(giveTPbar(int)), this, SLOT(setTPbar(int)));
    connect(threadList, SIGNAL(giveTPbarVal(int)), this, SLOT(setTPbarVal(int)));
    connect(threadList, SIGNAL(finished()), this, SLOT(launchDownload()));
    threadList->start();
}

void MainWindow::setModel(QStringListModel *modele)
{
    file_list = modele->stringList();
    ui->lv->setModel(modele);
}
void MainWindow::setTPbar(int size)
{
    ui->total_pbar->setMaximum(size);
}
void MainWindow::setTPbarVal(int val)
{
    ui->total_pbar->setValue(val);
}

/*
    QString fileName("update.lst");
    QFile fichier(fileName);
    fichier.open(QIODevice::ReadOnly);
    QTextStream flux(&fichier);
    QString ligne;
    while(!flux.atEnd())
    {
        ligne = flux.readLine();
        if (ligne == "[misc]")
        {
            ligne = flux.readLine();
            addr_server = ligne.section('=', 1, 1);
        }
        else if (ligne == "[files]")
        {
            ligne = flux.readLine();
            file_count = ligne.section('=', 1, 1).toInt();
            int i = 0;
            while (i < file_count)
            {
                ligne = flux.readLine();
                if (critical == false || ligne.section('|', 2, 2) == "c")
                {
                    if (CalcSha1(ligne.section('|', 0, 0).section('=', 1, 1)) != ligne.section('|', 1, 1)){
                        file_list.append(ligne.section('=', 1, 1).section('|', 0, 0));
                    }
                }
                i++;
            }
        }
    }

    QStringListModel *modele = new QStringListModel(file_list);
  */

void MainWindow::updateDataReadProgress(int bytesRead, int totalBytes)
{
    ui->current_pbar->setMaximum(totalBytes);
    ui->current_pbar->setValue(bytesRead);
}

void MainWindow::launchDownload()
{
    delete threadList;
    setStatusLabel("All files checked");
    ui->FC_boutton->setEnabled(false);
    ui->start_boutton->setEnabled(false);
    ThreadDownload = new TDownload(this, file_list);
    connect(ThreadDownload, SIGNAL(updateProgress(int, int)), this, SLOT(updateDataReadProgress(int,int)));
    connect(ThreadDownload, SIGNAL(finished()), this, SLOT(dlFinish()));
    connect(ThreadDownload, SIGNAL(changeStatus(QString)), this, SLOT(setStatusLabel(QString)));
    connect(ThreadDownload, SIGNAL(done()), this, SLOT(increaseTotalCounter()));
    ThreadDownload->start();
}

void MainWindow::increaseTotalCounter()
{
    ui->total_pbar->setValue(ui->total_pbar->value() + 1);
}

void MainWindow::dlFinish()
{
    ui->FC_boutton->setEnabled(true);
    ui->start_boutton->setEnabled(true);
    setStatusLabel("All file up to date, if you haven't play the game since 2 week click on full check button");
    delete ThreadDownload;
}

void MainWindow::setStatusLabel(QString info)
{
    ui->statusLabel->setText(info);
}
